package cc.shacocloud.mirage.utils.converter.support;

import cc.shacocloud.mirage.utils.ClassUtil;
import cc.shacocloud.mirage.utils.converter.ConversionException;
import cc.shacocloud.mirage.utils.converter.ConversionSupport;
import cc.shacocloud.mirage.utils.converter.TypeDescriptor;
import org.jetbrains.annotations.NotNull;

/**
 * 转换为 {@link Class} 类型的转换器
 *
 * @author 思追(shaco)
 */
public class ToClassConversion extends AbstractConversion implements ConversionSupport {
    
    @Override
    public boolean support(@NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        Class<?> objectType = targetType.getObjectType();
        return Class.class.equals(objectType);
    }
    
    @Override
    public Object convert(@NotNull Object source, @NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        if (source instanceof Class) {
            return source;
        }
        
        try {
            return Class.forName(convertToStr(source), false, ClassUtil.getDefaultClassLoader());
        } catch (ClassNotFoundException e) {
            throw new ConversionException(sourceType, targetType, source, e);
        }
    }
}
